<?php

class LoginController extends Sgit_Controller_Action
{
    protected $_checkAcceso = false;
    protected $_checkZona = false;
    protected $_checkSession = false;


    public function indexAction()
    {

    /*    
      $ua=$this->getBrowser();

      if(!in_array(strtolower(trim($ua['code'])),array('firefox','chrome','safari','opera')))
     
      {
            //$this->_helper->layout->disableLayout();
            $this->_helper->viewRenderer->setNoRender(TRUE);
        
        
        print $ua['code'];
            print '<h1>Error</h1>
                <h2>Access denied</h2>
                <p>Esta web no es accesible con '.$ua['name'].'</p>';
            exit();

      }
*/
        
        
        $form = new Application_Form_Login();

        $request = $this->getRequest();
        $this->_redirector = $this->_helper->getHelper('Redirector');

        if ($request->isPost())
        {

            if ($form->isValid($request->getPost()))
            {


                $values = $form->getValues();


                $auth = Zend_Auth::getInstance();

                $adapter = new Sgit_Auth_Adapter_MyAuth();


                $adapter->setUsername($values['username']);
                $adapter->setPassword($values['password']);


                $result = $auth->authenticate($adapter);


                switch ($result->getCode())
                {
                    case (Zend_Auth_Result::FAILURE):
                        $this->view->errorMessage = array_shift($result->getMessages());
                        break;
                    case (Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND):
                        $this->view->errorMessage = array_shift($result->getMessages());
                        break;
                    case (Zend_Auth_Result::SUCCESS):
                        $user = $adapter->getResultRowObject();
                        $auth->getStorage()->write($user);


                        $this->habilitarSgitViejo($user);

                                
                        $destino=$values['destino'];
                        if ($destino)
                        {
                            header("Location: $destino");
                            exit();
                        } else
                        {
                      
                            //header('Location:index.php?modulo=Index');exit();
                            $this->_redirector->setGotoSimple("index","index",null,array('c'=>c));                  
           
                        }
                    default:
                        $this->view->errorMessage = 'Fallo desconocido';
                        break;
                }
            }
        }

        $destino = urldecode(base64_decode($request->getParam('destino')));

        $this->view->form = $form;
        $this->view->destino = $destino;
    }

    public function logoutAction()
    {
        Zend_Auth::getInstance()->clearIdentity();
        Zend_Session::destroy();
        $this->_helper->redirector('index'); // back to login page
    }


    protected function _process($values)
    {


        // Get our authentication adapter and check credentials
        $dbAdapter = Zend_Db_Table::getDefaultAdapter();
        $adapter = new Zend_Auth_Adapter_DbTable($db);
        $adapter->setTableName('usuarios')->setIdentityColumn('usuario')->setCredentialColumn('password')->setIdentity($values['username'])->setCredential($values['password']);


        $auth = Zend_Auth::getInstance();
        $result = $auth->authenticate($adapter);

        if ($result->isValid())
        {
            $user = $adapter->getResultRowObject(null, 'password');
            $auth->getStorage()->write($user);
            return true;
        }
        return false;
    }


    protected function _getAuthAdapter()
    {

        $dbAdapter = Zend_Db_Table::getDefaultAdapter();
        $authAdapter = new Zend_Auth_Adapter_DbTable($db);

        $authAdapter->setTableName('usuarios')->setIdentityColumn('usuario')->setCredentialColumn('password');

        return $authAdapter;
    }


    protected function habilitarSgitViejo($row)
    {

        $_SESSION['server']=$_SERVER['HTTP_HOST'];
        $_SESSION['user'] = $row->usuario;
        $_SESSION['nombre'] = $row->nombre;
        $_SESSION['id_usuario'] = $row->id;
        $_SESSION['grupos'] =$row->grupos;
        $_SESSION['superuser'] = false;

        $m_usuario =    new Application_Model_Usuario();
        $m_datacenter = new Application_Model_Datacenter();
        $m_facilities = new Application_Model_Facilitie();





        $superusers=Sgit_Util_UserByGroup::run(100);

        if (in_array($row->id, $superusers))
        {
            $_SESSION['superuser'] = true;
        }


        $zonas = $m_datacenter->cacheAssoc();
        $zonas = $m_datacenter->assocArray2($zonas,'id','nombre');
        $usuarios = $m_usuario->cacheAssoc();
        $usuarios = $m_usuario->assocArray2($usuarios,'id','nombre');
        $facilities = $m_facilities->getAssoc('id_zona','id_usuario');

        $_SESSION['zonas'] = $zonas;
        $_SESSION['usuarios'] = $usuarios;
        $_SESSION['facilities'] = $facilities;


    }
    
    
    function getBrowser()
    {
        $u_agent = $_SERVER['HTTP_USER_AGENT'];
        $bname = 'Unknown';
        $platform = 'Unknown';
        $version= "";
    
        //First get the platform?
        if (preg_match('/linux/i', $u_agent)) {
            $platform = 'linux';
        }
        elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
            $platform = 'mac';
        }
        elseif (preg_match('/windows|win32/i', $u_agent)) {
            $platform = 'windows';
        }
       
        // Next get the name of the useragent yes seperately and for good reason
        if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
        {
            $bname = 'Internet Explorer';
            $ub = "MSIE";
        }
        elseif(preg_match('/Firefox/i',$u_agent))
        {
            $bname = 'Mozilla Firefox';
            $ub = "Firefox";
        }
        elseif(preg_match('/Chrome/i',$u_agent))
        {
            $bname = 'Google Chrome';
            $ub = "Chrome";
        }
        elseif(preg_match('/Safari/i',$u_agent))
        {
            $bname = 'Apple Safari';
            $ub = "Safari";
        }
        elseif(preg_match('/Opera/i',$u_agent))
        {
            $bname = 'Opera';
            $ub = "Opera";
        }
        elseif(preg_match('/Netscape/i',$u_agent))
        {
            $bname = 'Netscape';
            $ub = "Netscape";
        }
       
        // finally get the correct version number
        $known = array('Version', $ub, 'other');
        $pattern = '#(?<browser>' . join('|', $known) .
        ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
        if (!preg_match_all($pattern, $u_agent, $matches)) {
            // we have no matching number just continue
        }
       
        // see how many we have
        $i = count($matches['browser']);
        if ($i != 1) {
            //we will have two since we are not using 'other' argument yet
            //see if version is before or after the name
            if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
                $version= $matches['version'][0];
            }
            else {
                $version= $matches['version'][1];
            }
        }
        else {
            $version= $matches['version'][0];
        }
       
        // check if we have a number
        if ($version==null || $version=="") {$version="?";}
       
        return array(
            'userAgent' => $u_agent,
            'code' => $ub,
            'name'      => $bname,
            'version'   => $version,
            'platform'  => $platform,
            'pattern'    => $pattern
        );
    }

    


}
